--[========================================================================[--

Main file for Thrust II Reloaded.

Copyright © 2015 Pedro Gimeno Fortea

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

--]========================================================================]--

require('lovespaces')

local volscale = 40
local volgrabbed = false

main = {}
local active, canvas

function main.activate(new)
  if active and active.deactivate then active.deactivate() end
  active = new
  if active.activate then active.activate() end
end

-- screens
splash = require('splash')
menu = require('menu')
redef = require('redef')
ready = require('getready')
game = require('game')
gameover = require('gameover')

-- modules that are not screens
main.map,
  main.enemytypes,
  main.enemies,
  main.orbs,
  main.decoys,
  main.targets,
  main.respawn,
  main.agents = require 'layout' ()

local mods_to_init = { splash, menu, redef, ready, game, gameover }


local function volume(vol, save)
  vol = (vol < 0) and 0 or vol
  vol = (vol > 1) and 1 or vol
  la.setVolume(vol^2)
  main.vol = vol

  if save then
    local tmp = main.vol .. ""
    lfs.write("vol.txt", tmp, #tmp)
  end
end

-- deepcopy from http://lua-users.org/wiki/CopyTable
-- minus the parts that we don't need
function main.deepcopy(orig)
  local orig_type = type(orig)
  local copy
  if orig_type == 'table' then
    copy = {}
    for orig_key, orig_value in next, orig, nil do
--      copy[deepcopy(orig_key)] = deepcopy(orig_value)
      copy[orig_key] = main.deepcopy(orig_value)
    end
    -- setmetatable(copy, deepcopy(getmetatable(orig)))
  else -- number, string, boolean, etc
    copy = orig
  end
  return copy
end


function love.load(args)
  argv = args

  if not lg.isSupported("canvas") then
    error("This application requires canvas support. Unfortunately your graphics card does not support it.")
  end

  lfs.setIdentity("ThrustIIreloaded")

  main.ww, main.wh = lw.getDimensions()
  canvas = lg.newCanvas(main.ww, main.wh)

  main.font = lg.newImageFont("img/Font16x16.png",
      " !\"#$%&'()*+,-./0123456789:;<=>?\127ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~@")
  lg.setFont(main.font)

  main.keys =
    { left = "q", right = "w", thrust = "p", pickup = "l", fire = " " }
  if lfs.isFile("keys.txt") then
    local line = 0
    for s in lfs.lines("keys.txt") do
      line = line + 1
      if line == 1 then
        main.keys.left = s
      elseif line == 2 then
        main.keys.right = s
      elseif line == 3 then
        main.keys.thrust = s
      elseif line == 4 then
        main.keys.pickup = s
      elseif line == 5 then
        main.keys.fire = s
      else
        break
      end
    end
  else
    local s = main.keys.left   .. "\n"
           .. main.keys.right  .. "\n"
           .. main.keys.thrust .. "\n"
           .. main.keys.pickup .. "\n"
           .. main.keys.fire
    lfs.write("keys.txt", s, #s)
  end

  main.vol = 0.5
  if lfs.isFile("vol.txt") then
    local tmp
    main.vol, tmp = lfs.read("vol.txt")
    volume(main.vol + 0)
  else
    volume(main.vol, true)
  end

  for i, mod in ipairs(mods_to_init) do
    if mod and mod.load then mod.load(arg) end
  end
  mods_to_init = nil

  -- Bootstrap activation
  main.activate(splash)

  -- Allow volume change with auto-repeat
  lk.setKeyRepeat(true)

  -- Used to end quit status on key release. Otherwise the key up event
  -- that led to releasing the quit status is registered.
  main.dontquit = false
  main.unpause = false
  main.singlestep = false
end

function love.update(dt)
  if volgrabbed then
    volume((lmo.getX() - (main.ww/2 + 108)) / volscale)
  end
  if main.paused and not main.singlestep or main.quitrequest then return end
  if active.update then active.update(main.singlestep and 0.03125 or dt) end
end

local function roundrect(x, y, w, h, r)
  lg.setStencil(
    function()
      lg.rectangle("fill", x, y+r, w, h-2*r)
      lg.rectangle("fill", x+r, y, w-2*r, h)
      lg.circle("fill", x+r, y+r, r, 10)
      lg.circle("fill", x+w-r, y+r, r, 10)
      lg.circle("fill", x+r, y+h-r, r, 10)
      lg.circle("fill", x+w-r, y+h-r, r, 10)
    end
  )
  lg.rectangle("fill", x, y, w, h)
  lg.setStencil()
end

function main.centertext(text, x, y)
  lg.print(text, x-main.font:getWidth(text)/2, y-main.font:getHeight()/2)
end

function love.draw()
  if main.quitrequest then
    lg.setColor(85, 85, 85, 255)
    lg.rectangle("fill", 0, 0, main.ww, main.wh)
    lg.setColor(255, 255, 255, 120)
    lg.draw(canvas, 0, 0)
    lg.setColor(0, 0, 0, 200)

    roundrect(main.ww/2-130, main.wh/2-50, 260, 100, 7)
    lg.setColor(255, 255, 255, 255)
    main.centertext("REALLY QUIT?", main.ww/2, main.wh/2 - 20)

    lg.setColor(160, 240, 200)
    roundrect(main.ww/2-70, main.wh/2+4, 60, 24, 4)
    lg.setColor(240, 200, 160)
    roundrect(main.ww/2+10, main.wh/2+4, 60, 24, 4)
    lg.setColor(0, 0, 0, 255)
    main.centertext("YES", main.ww/2-40, main.wh/2+16)
    main.centertext("NO", main.ww/2+40, main.wh/2+16)
    lg.setColor(255, 255, 255, 255)
  else
    lg.setColor(255, 255, 255, 255)
    if main.paused and not main.singlestep then
      lg.draw(canvas, 0, 0)
      lg.setColor(64, 64, 64, 150)
      roundrect(main.ww/2-60, main.wh-44, 120, 40, 10)
      lg.setColor(255, 255, 255, 255)
      main.centertext("PAUSED", main.ww/2, main.wh - 24)
    else
      canvas:clear()
      if active.draw then canvas:renderTo(active.draw) end
      lg.draw(canvas, 0, 0)
    end
  end

  -- volume control

  local half = main.ww/2
  local volx = main.vol*volscale
  lg.setInvertedStencil(function()
      lg.setColor(255,255,255,255)
      lg.rectangle("fill", half + 103 + volx, main.wh-32, 10, 24)
     end)
  lg.setColor(0,0,0, 40)
  lg.polygon("fill", half + 92, main.wh - 11,
                     half + 155, main.wh - 11,
                     half + 155, main.wh - 29)
  lg.setColor(255, 255, 255, 60)
  lg.polygon("fill", half + 100, main.wh - 12,
                     half + 154, main.wh - 12,
                     half + 154, main.wh - 28)
  lg.setStencil()
  lg.setColor(0, 0, 0, 40)
  lg.rectangle("fill", half + 103 + volx, main.wh-32, 10, 24)
  lg.setColor(255, 255, 255, 70)
  lg.rectangle("fill", half + 104 + volx, main.wh-31, 8, 22)
  lg.setColor(255, 255, 255)
  if main.singlestep then main.singlestep = false end
end

function love.quit()
  if not main.quitaccepted then
    main.quitrequest = true
    main.dontquit = false
    if not main.paused and active.pause then active.pause(true) end
    return true -- don't quit
  end
end

function love.mousepressed(x, y, b)
  if main.quitrequest then
    if x >= main.ww/2-70 and x <= main.ww/2-10
       and y >= main.wh/2+4 and y <= main.wh/2+28
    then
      main.quitaccepted = true
      le.quit()
    elseif x >= main.ww/2+10 and x <= main.ww/2+70
       and y >= main.wh/2+4 and y <= main.wh/2+28
    then
      main.quitrequest = false
      if not main.paused and active.pause then active.pause(false) end
    end
  end

  if y >= main.wh-32 and y <= main.wh-8
    and  x >= main.ww/2 + 104 + main.vol*volscale
    and x <= main.ww/2 + 112 + main.vol*volscale
  then
    lmo.setGrabbed(true)
    volgrabbed = true
    volume((x - (main.ww/2 + 108)) / volscale)
  end
end

--[[ (not in 0.9.1 - handled in love.update())
function love.mousemoved(x, y, dx, dy)
  if volgrabbed then
    volume((x - (main.ww/2 + 108)) / volscale)
  end
end
]]

function love.mousereleased(x, y, b)
  if volgrabbed then
    lmo.setGrabbed(false)
    volgrabbed = false
    volume((x - (main.ww/2 + 108)) / volscale, true)
  end
end

function love.keypressed(k, r)
  if k == "kp-" or k == "kp+" then
    volume(main.vol + (k == "kp+" and 0.0625 or -0.0625), true)
  elseif r then
    -- nothing
  elseif main.quitrequest then
    if k == "escape" then
      main.dontquit = true
    end
  elseif k == "escape" then
    le.quit()
  elseif k == "pause" and not main.quitrequest and
      -- ctrl + pause = break, that breaks the game and must be passed down
      not (lk.isDown("lctrl") or lk.isDown("rctrl") or lk.isDown("ctrl"))
  then
    main.paused = not main.paused
    if active.pause then active.pause(main.paused) end
  elseif active.keypressed then
    active.keypressed(k, r) 
  end
  --[[ debug ]]
  --if k == "1" and main.paused then main.singlestep = true end
  --]]
end

function love.textinput(c)
  if main.quitrequest then
    if c:lower() == "y" then
      main.quitaccepted = true
      le.quit()
    elseif c:lower() == "n" then
      main.dontquit = true
    end
    return
  end
  if active.textinput then active.textinput(c) end
end

function love.keyreleased(k)
  if main.quitrequest then
    if main.dontquit then
      main.dontquit = false
      main.quitrequest = false
      if not main.paused and active.pause then active.pause(false) end
    end
  elseif k ~= "pause" then
    if active.keyreleased then active.keyreleased(k) end
  end
end
